package com.example.api;

import com.alibaba.fastjson.JSONObject;
import com.example.helper.JwtHelper;
import com.example.model.user.UserInfo;
import com.example.result.Result;
import com.example.service.UserInfoService;
import com.example.utils.ConstantWxPropertiesUtils;
import com.example.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

//微信操作接口
@Slf4j
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;

    //微信扫描后回调的方法
    @GetMapping("callback")
    public String callback(String code,String state){
        //获得临时票据code
        System.out.println("code = " + code);
        //拿着code和微信id和秘钥 请求固定地址 得到两个值
        //使用code和APPID以及appSecret换取access_token

        // %s 占位符
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantWxPropertiesUtils.WX_OPEN_APP_ID,
                ConstantWxPropertiesUtils.WX_OPEN_APP_SECRET,
                code);
        //使用httpClient请求地址
        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            log.info("accessTokenInfo={}",accessTokenInfo);

            //从返回的字符串获取access_token和openid
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //判断数据库中是否已经存在微信扫码人信息 根据openID进行判断
            UserInfo userInfo=userInfoService.selectWxInfoOpenId(openid);
            if (userInfo==null){//数据库不存在微信信息
                //拿着access_token和openid请求微信地址 得到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                log.info("resultInfo={}",resultInfo);
                JSONObject resultInfoJson = JSONObject.parseObject(resultInfo);
                //解析用户信息
                String nickname = resultInfoJson.getString("nickname");
                String headimgurl = resultInfoJson.getString("headimgurl");
                //获取扫码人信息添加到数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }

            //返回name和token字符串
            HashMap<String, String> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            //判断userInfo是否有手机号 如果为空 返回openID
            //如果手机号不为空 返回openID值是空字符串
            //前端判断 如果openID不为空 绑定手机号；如果为空 不需要绑定手机号
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            //生成token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);

            return "redirect:" + ConstantWxPropertiesUtils.YYGH_BASE_URL +
                    "/weixin/callback?token="+map.get("token")+
                    "&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"),"UTF-8");

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //生成微信扫描二维码
    //返回生成二维码需要的参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect(){
        HashMap<String, Object> map = new HashMap<>();
        String redirectUri = null;
        try {
            map.put("appid", ConstantWxPropertiesUtils.WX_OPEN_APP_ID);
            map.put("scope", "snsapi_login");
            String wxOpenRedirectUrl = ConstantWxPropertiesUtils.WX_OPEN_REDIRECT_URL;
            redirectUri = URLEncoder.encode(wxOpenRedirectUrl, "UTF-8");
            map.put("redirect_uri",redirectUri);
            map.put("state", System.currentTimeMillis()+"");//System.currentTimeMillis()+""
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    //回调方法、得到扫描人信息
}
